package com.sjzl.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.sjzl.entity.Post;
import com.sjzl.entity.PostVisitor;
import com.sjzl.entity.User;
import com.sjzl.service.PostService;
import com.sjzl.service.PostVisitorService;
import com.sjzl.service.UserService;

@Component("postVisitorServiceImpl")
public class PostVisitorServiceImpl extends ServiceImpl<PostVisitor> implements
		PostVisitorService {

	@Resource(name = "postServiceImpl")
	private PostService postService;
	
	@Resource(name = "userServiceImpl")
	private UserService userService;

	@Override
	public void create(PostVisitor entity) {
		// TODO Auto-generated method stub

	}

	@Transactional
	public void saveOrUpdateVisitors(String vusername, Integer post_id) {
		User dbUser = userService.getUserByAccount(vusername);
		if (vusername == null) {
			return;
		}
		Post p = postService.get(Post.class, post_id);
		PostVisitor pv = new PostVisitor();
		pv.setVusername(vusername);
		pv.setHeadImageSrc(dbUser.getHeadImageSrc());
		pv.setDateCreated(new Date());
		pv.setPost(p);
		this.getDao().save(pv);
	}

	@Transactional
	public List<PostVisitor> getTodayVisitors(Integer post_id) {
		//SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
		//String nowDate = f.format(new Date());
		//List<PostVisitor> todayVisitors = new ArrayList<PostVisitor>();
		Post p = postService.get(Post.class, post_id);
		List<PostVisitor> list = p.getPostVisitors();
		List<PostVisitor> list2 =new ArrayList<PostVisitor>();
		Date d= new Date();
		GregorianCalendar g =new GregorianCalendar();
		g.setTime(d);
		int nowDay =g.get(Calendar.DAY_OF_YEAR);
		for(PostVisitor pv :list){
			g.setTime(pv.getDateCreated());
			int beforDay = g.get(Calendar.DAY_OF_YEAR);
			if(nowDay == beforDay){
				list2.add(pv);
			}
		}
		System.out.println(list2.size());
		List<PostVisitor> list3 =new ArrayList<PostVisitor>();
		for(PostVisitor pv :list2){
			list3.add(pv);// 不可直接list3= list2;
		}
		for (int i = 0; i < list3.size(); i++) {
			for (int j = i + 1; j < list3.size(); j++) {
				if (list3.get(i).getVusername().equals(list3.get(j).getVusername())) {
					list3.remove(j);
					j--;// 这一句不要忘了
				}
			}
		}
		for(int i =0;i<list3.size();i++){
			long a =list3.get(i).getDateCreated().getTime();
				for(int j =0 ;j<list2.size();j++){
					if(list3.get(i).getVusername().equals(list2.get(j).getVusername())){
						long b =list2.get(j).getDateCreated().getTime();
						if(b > a ){
							System.out.println(b);
							list3.set(i, list2.get(j));
						}
					}
				}
		}

		return list3;
	}

}
